package com.icesnowsun.app.user.service.impl;

import ncme.auto.framework.core.entities.ResMsg;
import ncme.auto.framework.core.services.AutoEntityServiceImpl;
import ncme.auto.framework.core.services.callback.AutoProcessControllerPart;
import ncme.auto.framework.core.services.callback.AutoProcessInterface;
import ncme.auto.framework.core.services.entities.ParamConverter;
import ncme.auto.framework.core.services.entities.RelationInfo;
import ncme.auto.framework.core.services.entities.ServiceInfo;
import com.icesnowsun.app.user.entity.User;
import ncme.auto.framework.core.utils.JwtUtil;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends AutoEntityServiceImpl<User> {

    @Override
    public void customService(AutoProcessControllerPart autoProcessControllerPart, ServiceInfo serviceInfo) throws Throwable {
        autoProcessControllerPart.setAfterAddPartCallback(new AutoProcessInterface() {
            @Override
            public Object onCallBack() throws Throwable {
                serviceInfo.getParamConverter().getString("");
                return null;
            }
        });
    }

    @Override
    public List<RelationInfo> setRelatedEntityInfo(List<RelationInfo> relationInfos) {
        return null;
    }

    public Object login(ParamConverter paramConverter, Integer userId, String userName) throws Throwable {
        User user = getUser(paramConverter.getString("username"), paramConverter.getString("password"));   //查找User，该方法并非内置，需自行编写
        if (user != null) {    //User存在
            Map<String, String> map = new HashMap<>();
            map.put("userId", user.getId().toString());
            map.put("userName", user.getUsername());
            String token = JwtUtil.getToken(map);      //生成并保存token
            return ResMsg.successResOnlyToken(token);      //返回token
        } else {    //User不存在
            throw new LoginException("用户名或密码不正确");
        }
    }

    private User getUser(String username, String password) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        return getEntityByMap(map, false);
    }

}